package com.funcourse.demo.api.restful.security;

import com.funcourse.demo.WechatConfigurationsHolder;
import com.funcourse.demo.api.ApiSystemConstants;
import com.funcourse.demo.wechat.conf.WechatConfiguration;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WechatConfigFilter implements Filter {

  private static final Pattern refererPattern = Pattern.compile("https?://(.*).chongya.fun");

  @Autowired
  WechatConfigurationsHolder wechatConfigurationsHolder;

  @Override
  public void destroy() {

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String referer = httpRequest.getHeader("Referer");
    final String chongya = "chongya";
    if(null == referer){
      referer= chongya;
    }
    final Matcher refererMatcher = refererPattern.matcher(referer);
    if(refererMatcher.find()){
      referer=refererMatcher.group(1);
    }
    log.info("request from {} under {} is accessing {}",  httpRequest.getRemoteAddr(),
        referer,
        httpRequest.getRequestURL());
    WechatConfiguration wechatConfiguration = wechatConfigurationsHolder.getApps()
        .get(referer);
    if(null == wechatConfiguration){
      wechatConfiguration = wechatConfigurationsHolder.getApps().get(chongya);
    }
    request.setAttribute(ApiSystemConstants.SERVLET_ATTR_WECHAT_CONFIG, wechatConfiguration);
    chain.doFilter(request, response);
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {

  }

}
